package sfx;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * A playable Sound.
 * @author nick-luca.frank
 *
 */
public class Sound {
	private Clip clip;
	private File file;
	private AudioInputStream ais;
	private FloatControl volume;
	
	/**
	 * Loads the Sound's sound-file.
	 * @param soundfile the Path of the file to be loaded
	 */
	public Sound(File soundfile){
		file = soundfile;
	}
	
	/**
	 * Opens the Sound's sound-file.
	 */
	public void open(){
		if (file.exists()){
			try {
				clip = AudioSystem.getClip();
				ais = AudioSystem.getAudioInputStream(file);
				clip.open(ais);
				volume = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
			} catch (LineUnavailableException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (UnsupportedAudioFileException e) {
				e.printStackTrace();
			}
		}else{
			System.out.println("TEST");
		}
		
	}
	
	/**
	 * Plays the sound starting at the frame-position 0.
	 */
	public void play(){
		clip.setFramePosition(0);
		clip.start();
	}
	
	/**
	 * Stops the sound.
	 */
	public void stop(){
		clip.stop();
	}
	/**
	 * @return whether the sound is currently playing
	 */
	public boolean isPlaying(){
		return clip.isRunning();
	}
	
	public void setVolume(float value){
		volume.setValue(value);
	}
	
	public float getVolume(){
		return volume.getValue();
	}
}
